package com.innovation.ic.b1b.monitor.web.config;

import com.innovation.ic.b1b.monitor.base.pojo.constant.config.DatabaseGlobal;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value = -100)
@Aspect
public class DataSourceAspect {

    private static final Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("execution(* com.innovation.ic.b1b.monitor.base.service.sharding.impl..*.*(..))")
    private void b1bMonitorShardingAspect() {
    }

    @Before("b1bMonitorShardingAspect()")
    public void b1bMonitorSharding(JoinPoint joinPoint) {
        log.debug("切换到{} 数据源...", DatabaseGlobal.B1B_MONITOR_SHARDING);
        DynamicDataSourceContextHolder.setDataSourceKey(DatabaseGlobal.B1B_MONITOR_SHARDING);
    }

    @Pointcut("execution(* com.innovation.ic.b1b.monitor.base.service.masterSlave.impl..*.*(..))")
    private void b1bMonitorMasterSlaveAspect() {
    }

    @Before("b1bMonitorMasterSlaveAspect()")
    public void b1bMonitorMasterSlave(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            log.debug("切换到{} 数据源...", DatabaseGlobal.B1B_MONITOR_MASTER_SLAVE);
            DynamicDataSourceContextHolder.setMainDataSource();
            return;
        }
        Object arg = args[args.length - 1];
        if (arg instanceof Boolean) {
            Boolean mainDataSource = (Boolean) arg;
            if (mainDataSource == true) {
                log.debug("切换到{} 数据源...", DatabaseGlobal.B1B_MONITOR2);
                DynamicDataSourceContextHolder.setMainDataSource();
            } else {
                log.debug("切换到{} 数据源...", DatabaseGlobal.B1B_MONITOR_MASTER_SLAVE);
                DynamicDataSourceContextHolder.setDataSourceKey(DatabaseGlobal.B1B_MONITOR_MASTER_SLAVE);
            }
        } else {
            log.debug("切换到{} 数据源...", DatabaseGlobal.B1B_MONITOR_MASTER_SLAVE);
            DynamicDataSourceContextHolder.setMainDataSource();
        }
    }

    @Pointcut("execution(* com.innovation.ic.im.end.base.service.impl..*.*(..))")
    private void imAspect() {
    }

    @Before("imAspect()")
    public void imMonitor(JoinPoint joinPoint) {
        log.debug("切换到{} 数据源...", DatabaseGlobal.IM);
        DynamicDataSourceContextHolder.setDataSourceKey(DatabaseGlobal.IM);
    }

}
